package br.org.bertol.orion.admin.internal;

import java.io.File;
import java.util.Map;
import oracle.oc4j.admin.jmx.shared.util.DataSink;
import oracle.oc4j.admin.jmx.shared.util.EarFileUtils;
import oracle.oc4j.admin.management.shared.SharedModuleType;
import com.evermind.server.ApplicationServer;

public class OrionDeployerFactory
{

	public OrionDeployerFactory ()
	{
	}

	public static OrionDeployerIF getInstance (ApplicationServer server, DataSink sink,
	    String deploymentName, SharedModuleType moduleType, Map extraParams)
	{
		checkParams(deploymentName, moduleType);

		if (moduleType.equals(SharedModuleType.EAR))
		    return new OrionApplicationDeployer(server, sink, deploymentName, extraParams);

		String contextRoot = null;

		if (moduleType.equals(SharedModuleType.WAR)) contextRoot = getContextRoot(extraParams);

		final File earFile = EarFileUtils.toEar(sink, moduleType, deploymentName, contextRoot);

		DataSink newSink = new DataSink(earFile.getAbsolutePath());
		newSink.setUploadId(sink.getUploadId());
		newSink.setTempFile(true);

		OrionApplicationDeployer deployer = new OrionApplicationDeployer(server, newSink,
		    deploymentName, extraParams);

		return deployer;
	}

	private static void checkParams (String deploymentName, SharedModuleType moduleType)
	{
		if (deploymentName == null)
		    throw new IllegalArgumentException(
		        "OrionDeployerFactory.getInstance(), deploymentName can not be null!");
		if (moduleType == null)
			throw new IllegalArgumentException(
			    "OrionDeployerFactory.getInstance(), moduleType cannot be null!");
		else
			return;
	}

	private static String getContextRoot (Map extraParams)
	{
		if (extraParams == null || !extraParams.containsKey("contextRoot"))
			throw new IllegalArgumentException(
			    "OrionDeployerFactory.getInstance(), for .war file, <contextRoot> should be specified in extraParms!");
		else
			return (String)extraParams.get("contextRoot");
	}
}
